package com.lucene.blog.realm;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.lucene.blog.bean.Blogger;
import com.lucene.blog.db.service.BloggerService;

/**
 * 自定义realm
 * @author yachao
 *
 */
public class MyRealm extends AuthorizingRealm {

	@Resource
	private BloggerService bloggerService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 该项目只有一个用户，所以用不到（权限验证）
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		try {
			// 登录验证
			String nickname = (String) token.getPrincipal();
			Blogger blogger = bloggerService.getBloggerByNickname(nickname);
			
			if(blogger != null) {
				SecurityUtils.getSubject().getSession().setAttribute("currentUser", blogger);
				AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(blogger.getNickname(), blogger.getPassword(), "MyRealm");
				return authcInfo;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
